import Dialog from '../../vant-weapp/dialog/dialog';
import Toast from '../../vant-weapp/toast/toast';
import fw from '../../core/framework.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    device: {},
    warn: {
      diedao: false,
      lichuang: false,
      paihuai: false,
      check: false
    },
    config: {
      name: false,
      push: false
    },
    ws: null,
    wsTimer: null,
    $canvas: null,
    canvas_res:null,
    canvasBg:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var self = this;
    this.setData({
      device: typeof options.device == 'string' ? JSON.parse(options.device) : options.device
    })
    console.log(options.device)
    wx.createSelectorQuery().select('#myCanvas').node().exec((res) => {
      self.setData({
        $canvas: res[0].node,
        canvas_res:res
      })
      // self.render(res[0].node);
      self.getCanvasFnOpts(function(){
        self.startConnect();
      })
    });
    if(this.data.device.bg_url){
        self.setData({
          canvasBg:'background-image:url('+fw.url.getBaseScreenShotsURL()+this.data.device.bg_url+')'
        })
    }
    wx.setNavigationBarTitle({
      title: this.data.device.name
    });
  },
  getCanvasFnOpts(callbackFn){
    if(!fw.config.canvasFnOpts.server){
      fw.ajax('config/findByCode',{code:'canvas_fn_opts'}).then(res=>{
        if(res.code == 0){
          fw.config.canvasFnOpts.server = JSON.parse(res.data.value);
          callbackFn();
        }else{
          callbackFn();
        }
      })
    }else{
      callbackFn();
    }
  },
  getData(){
    var self = this;
    fw.ajax("device/read",{id:self.data.device.id}).then(res=>{
        if(res.code == 0){
          self.setData({
            device:res.data
          });
          if(res.data.bg_url){
            self.setData({
              canvasBg:'background-image:url('+fw.url.getBaseScreenShotsURL()+res.data.bg_url+')'
            })
          }
        }
    });
  },
  test() {
    let canvas = this.data.$canvas
    var ctx = canvas.getContext("2d");
    canvas.width = canvas._width;
    canvas.height = canvas._height;


    const dpr = wx.getSystemInfoSync().pixelRatio

    ctx.scale(dpr, dpr)

    ctx.fillRect(30, 0, 100, 100)
    console.log(canvas.width, canvas.height)
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  camera(){
    var self = this;
    var device = self.data.device;
    var _camera = function(){
      console.log('执行拍照')
      Toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true,
        message: '拍照处理中...'
      });
      fw.ajax('device/camera',{id:device.id,code:device.code,timeout:5*60*1000}).then(res=>{
        Toast.clear();
        if(res.code == 0){
            fw.ajax('device/update',{id:device.id,bg_url:res.data}).then(r=>{
              self.getData();
            })
        }else{
          Toast.fail({message:'拍照失败，请检查设备网络连接后重试。',duration:5000})
        }
      })
    };
    if(device.bg_url){
      Dialog.confirm({
        title: '提示',
        message: '确定重新拍照，覆盖原有地面图片？',
      }).then(() => {
        _camera();
      }).catch(() => {
       
      });
    }else{
      _camera();
    }
    console.log('camera',this.data.device)
  },
  setWarn(e) {
    var type = fw.getTargetData(e, 'type');
    var _value = e.detail;
    console.log(type, _value)
    this.setData({
      ['warn.' + type]: _value
    })
  },
  setConfig(e) {
    var type = fw.getTargetData(e, 'type');
    var _value = e.detail;
    this.setData({
      ['config.' + type]: _value
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.onUnload();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    var self = this;
    if (self.data.ws.readyState == self.data.ws.OPEN) {
      self.wsSend({
        code: 0,
        method: 1000,
        data: {
          device_id: self.data.device.id, // 摄像头id
          device_code: self.data.device.code, // 摄像头code
          status: 0 // 值为1，表示开始获取骨架图数据，值为0，表示结束
        }
      });
      self.data.ws.close();
    }
    if (self.data.wsTimer) clearTimeout(self.data.wsTimer);
  },
  startConnect: function () {
    let self = this;
    let device = self.data.device;
    //本地测试使用 ws协议 ,正式上线使用 wss 协议
    let url = fw.config.PARAM.API_WS + "/" + device.id + "/device";
    self.setData({
      ws: wx.connectSocket({
        url: url,
        method: "GET"
      })
    });
    self.data.ws.onOpen(res => {
      self.wsSend({
        code: 0,
        method: 1000,
        data: {
          device_id: device.id,
          device_code: device.code,
          status: 2
        }
      });
    });
    self.data.ws.onError(res => {
      console.info('连接异常');
      console.error(res);
    });
    self.data.ws.onMessage(res => {
      var data = res.data;
      // console.log('get msg ----------->', res);
      if (data) {
        var wsData = typeof data == 'string' ? JSON.parse(data) : data;
        if (self.data.wsTimer) clearTimeout(self.data.wsTimer);
        if (wsData.code == 0) {
          // console.log('-------?>', wsData);
          if(wsData.data.data != ' '){
            self.render(wsData.data.data);
          }
        } else {
          self.setData({
            wsTimer: setTimeout(function () {
              self.wsSend({
                code: 0,
                method: 1000,
                data: {
                  device_id: device.id,
                  device_code: device.code,
                  status: 2
                }
              });
            }, 3000)
          })
        }
      }
    });
    self.data.ws.onClose(() => {
      console.info('连接关闭');
    });
  },
  wsSend(data) {
    if (this.data.ws.readyState == this.data.ws.OPEN) {
      this.data.ws.send({
        data: JSON.stringify(data),
        success: () => {
          console.info('客户端发送成功');
        }
      });
    } else {
      console.error('连接已经关闭');
    }
  },
  render(data_str) {
    let canvas = this.data.$canvas;
    var context = canvas.getContext("2d");
    canvas.width = canvas._width;
    canvas.height = canvas._height;
    context.scale(0.5, 0.5);
    var pairs_array = fw.config.canvasFnOpts.server || fw.config.canvasFnOpts.local;
    var num_lines = pairs_array.length / 2;
    // var data_str= `0 0 427 175 386 191 386 280 382 345 469 160 479 198 0 0 420 241 401 245 0 0 0 0 443 237 426 310 0 0 426 175 444 174 404 160 459 158 0 0 0 0 0 0 0 0 0 0 0 0 0 0 427 175 386 191 386 280 382 345 469 160 479 198 0 0 420 241 401 245 0 0 0 0 443 237 426 310 0 0 426 175 444 174 404 160 459 158 0 0 0 0 0 0 0 0 0 0 0 0 0 0 427 175 386 191 386 280 382 345 469 160 479 198 0 0 420 241 401 245 0 0 0 0 443 237 426 310 0 0 426 175 444 174 404 160 459 158 0 0 0 0 0 0 0 0 0 0 0 0 `;
     /*var data_str = '354.500275 202.206665 \
338.641968 211.884003 \
299.137970 216.308609 \
273.660645 275.110077 \
271.924194 321.670593 \
376.442017 208.379791 \
396.576538 265.451050 \
378.189545 288.300903 \
336.910980 296.183044 \
311.422058 297.942657 \
0.000000 0.000000 \
0.000000 0.000000 \
362.371643 293.570374 \
0.000000 0.000000 \
0.000000 0.000000 \
346.548218 193.405060 \
363.275848 191.663666 \
326.337830 186.380722 \
372.032257 184.642960 \
0.000000 0.000000 \
0.000000 0.000000 \
0.000000 0.000000 \
0.000000 0.000000 \
0.000000 0.000000 \
0.000000 0.000000 \
197.930389 47.878265 \
179.292542 74.058601 \
145.623077 76.588310 \
96.973045 123.895218 \
133.151382 172.530273 \
214.195999 67.829689 \
244.123795 101.498146 \
236.651367 150.134903 \
189.218964 186.304611 \
169.274887 192.517883 \
180.577911 261.094391 \
189.292053 310.953369 \
209.160919 183.778748 \
211.716492 252.359772 \
199.227905 244.904984 \
186.746887 37.900547 \
202.974609 35.468132 \
164.305847 35.444492 \
0.000000 0.000000 \
207.968384 259.841797 \
215.455444 256.088898 \
199.212830 241.153671 \
198.003738 319.685455 \
189.224030 323.383667 \
193.005371 313.424500';*/

    var data_array = data_str.split(" ");

    var num_people = data_array.length / 50;
    for (var p = 0; p < num_people; ++p) {
      for (var i = 0; i < num_lines; ++i) {
        var idx_1 = 2 * pairs_array[2 * i];
        var idx_2 = 2 * pairs_array[2 * i + 1];

        var pt_1_x = data_array[idx_1 + p * 50];
        var pt_1_y = data_array[idx_1 + 1 + p * 50];
        var pt_2_x = data_array[idx_2 + p * 50];
        var pt_2_y = data_array[idx_2 + 1 + p * 50];

        if (Number(pt_1_x) > 10 && Number(pt_1_y) > 10 && Number(pt_2_x) > 10 && Number(pt_2_y) > 10) {
          context.beginPath();
          context.moveTo(Number(pt_1_x), Number(pt_1_y));
          context.lineTo(Number(pt_2_x), Number(pt_2_y));
          context.lineWidth = 3;
          context.strokeStyle = "red";
          context.stroke();
          context.closePath();
        }

      }
    }
  }
})